#include "stdafx.h"
#include "XAutoBufferImpl.h"

IMPLEMENT_SKIN_CLASS(CXAutoBufferImpl);

CXAutoBufferImpl::CXAutoBufferImpl()
{
    m_pData = NULL;
    m_dwSize = 0;
	m_dwRealSize = 0;
}
CXAutoBufferImpl::~CXAutoBufferImpl()
{
    ReleaseData();
}

// IXAutoBuffer
HRESULT CXAutoBufferImpl::GetBuffer(OUT void** pBuffer)
{
    return GetBuffer(pBuffer, m_dwSize);
}

HRESULT CXAutoBufferImpl::GetBuffer(OUT void** pBuffer, IN DWORD dwMinSize)
{
    if(dwMinSize <= m_dwRealSize)
    {
        *pBuffer = m_pData;
		m_dwSize = dwMinSize;
        return S_OK;
    }

    ReleaseData();

    m_dwRealSize = m_dwSize = dwMinSize;
    m_pData = XAllocArray(BYTE, dwMinSize);

    *pBuffer = m_pData;
    return S_OK;
}

HRESULT CXAutoBufferImpl::GetSize(OUT DWORD* pdwSize)
{
    *pdwSize = m_dwSize;
    return S_OK;
}

void CXAutoBufferImpl::OnFinalRelease()
{
    superclass::OnFinalRelease();
    ReleaseData();
}

void CXAutoBufferImpl::ReleaseData()
{
    if(m_pData != NULL)
    {
        XFreeArray((BYTE*)m_pData);
        m_pData = NULL;
        m_dwSize = 0;
		m_dwRealSize = 0;
    }
}

